<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>使用本地存储</title>
        <meta name="auther" content="wangjiale"/>
        <style>
            body>*{float:left;}
            table{border-collapse:collapse; margin-left:50px;}
            th,td{padding:4px;}
            th{text-align:right;}
            input{border:thin solid black; padding:2px;}
            label{min-width:50px; display:inline-block; text-align:right;}
            #buttons,#countmsg{margin-left:50px; margin-top:5px; margin-bottom:5px;}
        </style>
    </head>
    <body>
        <div>
            <div><label>Key:</label><input id="key" placeholder="Enter Key"/></div>
            <div><label>Value:</label><input id="value" placeholder="Enter Value"/></div>
            <div id="buttons">
                <button id="add">Add</button>
                <button id="clear">Clear</button>
            </div>
            <p id="countmsg">There are <span id="count"></span> items</p>
            <table id="data" border="1">
                <tr><th>Item Count:</th><td id="count">-</td></tr>
            </table>
        </div>
        <script>
            displayData();

            function displayData(){
                var tableElem=document.getElementById("data");
                tableElem.innerHTML="";
                var itemCount=localStorage.length;
                document.getElementById("count").innerHTML=itemCount;
                for(var i=0; i<itemCount; i++){
                    var key=localStorage.key(i);
                    var val=localStorage[key];
                    tableElem.innerHTML+="<tr><th>"+key+":</th><td>"+val+"</td></tr>";
                }
            }

            var buttons=document.getElementsByTagName("button");
            for(var i=0; i<buttons.length; i++){
                buttons[i].onclick=handleButtonPress;
            }

            function handleButtonPress(e){
                switch(e.target.id){
                    case 'add':
                        var key=document.getElementById("key").value;
                        var value=document.getElementById("value").value;
                        //浏览器不会删除用本地存储对象localStorage添加的数据，除非用户自己清除数据
                        localStorage.setItem(key,value);
                        break;
                    case 'clear':
                        localStorage.clear();
                        break;
                }
                displayData();
            }
        </script>
    </body>
</html>